package advancedKonwledgePdf;

import java.util.HashMap;

/**
 * @author clarence
 * 重写hashCode的原因展示
 */
public class OverWriteHashCodeTest {

    public static void main(String...args) {
        MyBean a = new MyBean();
        a.x = 1;
        a.s = "xyz";
        MyBean b = new MyBean();
        b.x = 1;
        b.s = "xyz";
        HashMap<MyBean, String> map = new HashMap<MyBean, String>(4);
        map.put(a, "a");
        map.put(b, "b");
        System.out.println("a equals b:"+a.equals(b));
        System.out.println("map size:"+map.size());
        System.out.println("a:"+map.get(a));
        System.out.println("b:"+map.get(b));
    }
}

class MyBean {
    int x;
    String s;
    @Override
    public boolean equals(Object obj) {
        if(this == obj) {
            return true;
        }
        if(!(obj instanceof MyBean)) {
            return false;
        }
        if(((MyBean)obj).x == x) {
            return true;
        }
        return false;
    }
}
class MyBean1 {
    int x;
    String s;
    @Override
    public boolean equals(Object obj) {
        if(this == obj) {
            return true;
        }
        if(!(obj instanceof MyBean)) {
            return false;
        }
        if(((MyBean)obj).x == x) {
            return true;
        }
        return false;
    }
    @Override
    public int hashCode() {
        return (s!=null?s.hashCode():1)*31+x;
    }
}
